package nmp.lib;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import nmp.lib.CNmpCmd.NmpWifiInfo;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.DhcpInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

public class CNmpWifiManage {

    private final String PREFERENCE_WIFILIST_PASSWORD = "WifiListPassword";
	private final int MAX_PREFERENCE_WIFI_PASSWORD_ITEM = 20;		
	private Context mContext;
	private ArrayList<NmpWifiInfo> mPrefPasswordList;
	private InetAddress m_broadcase_addr = null;
	private InetAddress m_gateway_addr = null;	
	private WifiManager mWifi = null;
	private WifiInfo mWifiinfo;
	private WifiInfo mLastWifiinfo;
	
	public CNmpWifiManage(Context context) {
		mContext = context;
		mWifi = (WifiManager)mContext.getSystemService(Context.WIFI_SERVICE);		
	}

	public boolean IsConnected(){
		return IsConnected(null);
	}
	
	public boolean IsConnected(String ssid){
				
        if(mWifi.isWifiEnabled()&&( mWifi.getWifiState()== WifiManager.WIFI_STATE_ENABLED)) {
        	
        	mWifiinfo = mWifi.getConnectionInfo();
        	
        	if(ssid != null) {
        		if(!mWifiinfo.getSSID().equals(ssid)) {
        			ReConnectToSSID(ssid);
        			return false;
        		}
        	}

        	DhcpInfo dhcp = mWifi.getDhcpInfo();
            int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;

            byte[] broadcase_quads = new byte[4];
            byte[] gateway_quads = new byte[4];
            for (int k = 0; k < 4; k++)
            {  
            	broadcase_quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
            	gateway_quads[k] = (byte) ((dhcp.gateway >> k * 8) & 0xFF);
            }
            
            Log.d(this.toString(),"IP address:"+ipAddr2String(dhcp.ipAddress));
            Log.d(this.toString(),"Net mask:"+ipAddr2String(dhcp.netmask));
            Log.d(this.toString(),"Getway:"+ipAddr2String(dhcp.gateway));
            Log.d(this.toString(),"broadcast:"+ipAddr2String(broadcast));
            
            try {
				m_broadcase_addr =  InetAddress.getByAddress(broadcase_quads);
				m_gateway_addr = InetAddress.getByAddress(gateway_quads);
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				mWifi = null;
				return false;
			}
            return true;            
        } else {
        	return false;
        }
    }	
	
	public String GetBroadcastAddress(){
		return m_broadcase_addr.getHostAddress();
	}
	
	public String GetGatewayAddress(){
		return m_gateway_addr.getHostAddress();
	}	
	
	public String GetWifiSSID(){
		if(mWifi == null || mWifiinfo == null)
			return null;
		return mWifiinfo.getSSID();
	}	
	
	public boolean ReConnectToSSID(String ssid){
		if(mWifi == null)
			return false;

		List<WifiConfiguration> ActiveWifiList;
		WifiConfiguration targetConfig = null;
		
		ActiveWifiList = mWifi.getConfiguredNetworks();
		
		ssid = "\""+ssid+"\"";
		
		for(WifiConfiguration wificonfig : ActiveWifiList) {
			Log.w(this.toString(),"SSID List:" + wificonfig.SSID + " == " + ssid);
			if(wificonfig.SSID.equals(ssid)) {				
				targetConfig = wificonfig;
				break;
			}
		}
		if(targetConfig == null) {
			Log.w(this.toString(),"Can not find SSID:" + ssid);
			return false;
		} else {
			Log.e(this.toString(),"enableNetwork:" + ssid);
			if(!mWifi.enableNetwork(targetConfig.networkId,true)) {
				Log.w(this.toString(),"enableNetwork error !!" + ssid);
			}else {
				//mWifi.reassociate();
				//mWifi.reconnect();				
			}
		}
		return true;
	}		
	
    static private String ipAddr2String(int address){
    	return String.format("%s,%d,%d,%d,%d",
        		"IP address:",address&0xFF,(address>>8)&0xFF,
        		(address>>16)&0xFF,(address>>24)&0xFF);
    }	
		
	public void UpdateWifiListPassword(ArrayList<NmpWifiInfo> wifilist) {
		
		if(wifilist == null)
			return;
		
		if(mPrefPasswordList == null) {
			mPrefPasswordList = PrefPasswordRead();
		}
		
		for(NmpWifiInfo info : wifilist) {
			for(NmpWifiInfo prefinfo : mPrefPasswordList) {
				if(info.ssid.equals(prefinfo.ssid)) {
					info.password =  prefinfo.password;
				}
			}
		}
	}

	public void PrefPasswordSet(String ssid, String password) {
		
		if(mPrefPasswordList == null) {
			mPrefPasswordList = PrefPasswordRead();
		}		
		NmpWifiInfo newitem = null;
		for(NmpWifiInfo prefinfo : mPrefPasswordList) {
			if(prefinfo.ssid.equals(ssid)) {
				newitem = prefinfo;
				mPrefPasswordList.remove(prefinfo);				
				break;
			}
		}
		
		if(newitem == null) {
			newitem = new NmpWifiInfo();
		} 
		newitem.password = password;
		newitem.ssid = ssid;
		mPrefPasswordList.add(newitem);
		if(mPrefPasswordList.size() > MAX_PREFERENCE_WIFI_PASSWORD_ITEM) {
			mPrefPasswordList.remove(0);
		}
	}
	

	public ArrayList<NmpWifiInfo> PrefPasswordGet() {	
		
		if(mPrefPasswordList == null) {
			mPrefPasswordList = PrefPasswordRead();
		}			
		return mPrefPasswordList;
	}	

	public void PrefPasswordSave() {	
		
		if(mPrefPasswordList == null) {
			//mPrefPasswordList = PrefPasswordRead();
			return;
		}	
		
		SharedPreferences settings = 
				mContext.getSharedPreferences(PREFERENCE_WIFILIST_PASSWORD, mContext.MODE_PRIVATE);
		Editor editor = settings.edit();
		
		editor.clear();
		for(NmpWifiInfo info: mPrefPasswordList) {
			editor.putString(info.ssid ,info.password);
			Log.e(this.toString(),"Save pref:" +info.ssid+","+info.password);
		}
		editor.commit();
	}
	
	private ArrayList<NmpWifiInfo> PrefPasswordRead() {
		
		SharedPreferences settings = 
				mContext.getSharedPreferences(PREFERENCE_WIFILIST_PASSWORD, mContext.MODE_PRIVATE);
		
		ArrayList<NmpWifiInfo> PrefPasswordList = new ArrayList<NmpWifiInfo>();
		
		Map<String, ?> map = settings.getAll();
		
		Log.e(this.toString(),"settings map:" + map.size());
		
		String value;		
		for(String key: map.keySet()) {
			value = (String) map.get(key);
			NmpWifiInfo info = new NmpWifiInfo();
			info.ssid = key;
			info.password = value;
			PrefPasswordList.add(info);
		}
		return PrefPasswordList;

	}	
	
	public void PrefPasswordTest() {
		SharedPreferences settings = 
				mContext.getSharedPreferences(PREFERENCE_WIFILIST_PASSWORD, mContext.MODE_PRIVATE);	
		
		Map<String, ?> map = settings.getAll();
		
		Log.e(this.toString(),"settings map:" + map.size());
		
		String tmp = null;
		
		for(String key: map.keySet()) {
			tmp = (String) map.get(key);
			Log.e(this.toString(),"settings test:" + tmp);
		}

		if(tmp == null)
		{	
			Log.e(this.toString(),"tmp==null");
			tmp = "walace";		
		}
		
		Editor editor = settings.edit();
		editor.putString("test1" ,tmp);
		editor.commit();		
	}


}
